package sicau.car.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.web.bind.annotation.*;

import sicau.car.entity.Application;
import sicau.car.result.R;
import sicau.car.service.ApplicationService;
import sicau.car.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ITcz
 * @since 2020-07-28
 */
@RestController
@RequestMapping("/userCar")
@CrossOrigin
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    ApplicationService applicationService;

    //CAS登陆样例
    @GetMapping("/loginIn")
    @ApiOperation("川农统一身份认证：登录")
    public R loginIn(HttpServletRequest request){
        HashMap<String, Object> map = new HashMap<>();
        String userName = "";
        Principal principal = request.getUserPrincipal();
        if (principal != null && principal instanceof AttributePrincipal) {
            AttributePrincipal aPrincipal = (AttributePrincipal) principal;
            //获取用户信息中公开的Attributes部分
            Map<String, Object> map1 = aPrincipal.getAttributes();
            userName = (String) map1.get("cn");   //刘一飞
            String userId = request.getRemoteUser();
            map.put("userId", userId); //73219
            map.put("userName", userName);
            request.getSession().setAttribute("userId", userId);
            request.getSession().setAttribute("userName", userName);
            System.out.println("登录"+map.toString());
            return R.ok(map);
        }else {
            return R.ok("获取账户信息失败");
        }
    }

    @GetMapping("/loginOut")
    @ApiOperation("川农统一身份认证：登出")
    public R loginOut(HttpServletResponse response, HttpSession session, HttpServletRequest request) throws IOException {
        session.invalidate();
        // ids的退出地址，ids6.wisedu.com为ids的域名  authserver为ids的上下文，logout为固定值
//        	String casLogoutURL = "http://ids6.wisedu.com/authserver/logout";
        String casLogoutURL = "https://authserver.sicau.edu.cn/authserver/logout";
        // service后面带的参数为应用的访问地址，需要使用URLEncoder进行编码
        //	String redirectURL=casLogoutURL+"?service="+URLEncoder.encode("http://ssodemo.wisedu.com:8080/caslogin.jsp");
        String redirectURL=casLogoutURL+"?service="+ URLEncoder.encode("https://carorder.sicau.edu.cn/SICAU/userCar/index/index.html");
        response.sendRedirect(redirectURL);
        return R.ok("已退出登录");
    }


    //plate_id=川AF59Z6&name=朱庆&beginDate=2017-12-26%2000:00:00&endDate=2017-12-26 00:59:59&phone=15328655210&reason=测试记录
    @PostMapping("Order")
    @ApiOperation("短期预约")
    public R order(@ApiParam("预约信息:plate_id=川AF59Z6&name=朱庆&beginDate=2017-12-26%2000:00:00&endDate=2017-12-26 00:59:59&phone=15328655210&reason=测试记录") @RequestBody Application application,
                   HttpServletRequest request){
        if(null == application) {
            return R.error(0, "预约信息为空");
        }
        Integer userId = Integer.valueOf(request.getHeader("userId"));
        if(userId == null ) {
            return R.error(500,"header里参数为空");
        }
        int userMonthlyFrequency = userService.getMonthlyFrequency(userId);
        if(userMonthlyFrequency < 0 || userMonthlyFrequency == 3){
            return R.error(0, "每个月最多预约3次");
        }
        application.setUserId(userId);
        int isSuccess = applicationService.order(application);
        if(isSuccess == 0) {
            return R.error(0, "申请失败");
        }else {
            //申请成功 给用户每月预约次数加一
            userService.addOne(userId);
            return R.ok("申请成功");
        }
    }

    @GetMapping("showOrder")
    @ApiOperation("显示自己的预约记录")
    public R showOrder(@ApiParam("页码") @RequestParam("page") int page,
                       @ApiParam("每页条数") @RequestParam("pageSize") int pageSize,
                       @RequestHeader("userId") String userid,HttpServletRequest request) {
        if(page > 0 && pageSize > 0) {
            Integer userId = Integer.valueOf(request.getHeader("userId"));
            if(userId == null) {
                return R.error(500, "header里参数为空");
            }
            IPage<Application> applicationIPage = userService.showOrder(page, pageSize, userId);
            if(applicationIPage != null) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("result",applicationIPage.getRecords());
                map.put("total",applicationIPage.getTotal());
                return R.ok(map);
            }else {
                return R.error(501, "获取信息失败");
            }
        }else {
            return R.error(0,"传入参数非法");
        }
    }



}

